<template>
  <el-container style="width: 200%;height: 100%;">
    <el-main style="width: 80%; margin: 0 auto; padding-top: 20px;">
      <el-card shadow="hover">
        <el-row :gutter="20">
          <!-- Image Section on the Left -->
          <el-col :span="10">
            <div class="image-gallery">
              <!-- Display images in two rows, three images per row -->
              <el-row :gutter="10">
                <el-col :span="8" v-for="(image, index) in productImages.slice(0, 3)" :key="index">
                  <div class="product-image-container">
                    <el-image
                        :src="image || defaultImage"
                        class="product-image"
                        :preview-src-list="productImages"
                        preview-teleported
                        :initial-index="index"
                    />
                    <div class="overlay-text">点击查看大图</div>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="10" style="margin-top: 10px;">
                <el-col :span="8" v-for="(image, index) in productImages.slice(3)" :key="index + 3">
                  <div class="product-image-container">
                    <el-image
                        :src="image || defaultImage"
                        class="product-image"
                        :preview-src-list="productImages"
                        preview-teleported
                        :initial-index="index + 3"
                    />
                    <div class="overlay-text">点击查看大图</div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-col>

          <!-- Text Section on the Right -->
          <el-col :span="14" style="padding-left:10%;">
            <div style="padding: 14px;">
              <h2 style="font-size: 24px; margin-bottom: 10px;">{{ product.name }}</h2>
              <p><strong>价格:</strong> <span style="color: red; font-size: 20px;">￥{{ product.price }}</span></p>
              <p><strong>重量:</strong> {{ product.weight }}g</p>
              <p><strong>积分:</strong> {{ product.point }}</p>
              <p><strong>环境保护系数:</strong> {{ product.epFactor }}</p>
              <p><strong>库存:</strong> {{ product.nums }}</p>
              <p><strong>描述:</strong> {{ product.description }}</p>
              <p><strong>卖家:</strong> {{ product.userName }}</p>
              <p><strong>上架时间:</strong> {{ formatTime(product.createTime) }}</p>
              <p><strong>更新时间:</strong> {{ formatTime(product.updateTime) }}</p>

              <!-- Quantity input -->
              <p><strong>选择数量:</strong></p>
              <el-input-number v-model="selectedQuantity" :min="1" :max="product.nums" label="商品数量"></el-input-number>
            </div>

            <!-- Buttons for operations -->
            <el-button type="primary" @click="gotoBuy(product.id )">购买</el-button>
            <el-button v-if="product.type !== 1" type="primary" @click="gotoExchange(userStore.UserId, product.userId, product.id)">
              交换
            </el-button>
            <el-button @click="addToCart">加入购物车</el-button>
            <el-button @click="gotoChat(product.userId, product.userName)">沟通</el-button>
          </el-col>
        </el-row>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref } from 'vue';
import { useRoute } from 'vue-router';
import { addCartAPI, getProductDetailAPI} from '@/api/Goods.js'; // Assuming API methods
import { checkExchangeAPI } from '@/api/Trade.js'; // Assuming API methods
import { ElMessage } from 'element-plus';
import router from "@/router/index.js";
import { useUserStore } from "@/stores/user";

// Store and route setup
const userStore = useUserStore();
const route = useRoute();
const product = ref({});
const productImages = ref([]);
const defaultImage = 'https://via.placeholder.com/400'; // Default image placeholder
const sellerId = ref(null);
const username = ref(null);
const selectedQuantity = ref(1); // Default quantity

// Fetch product details
const fetchProductDetail = async () => {
  try {
    const response = await getProductDetailAPI(route.query.productId);
    if (response.data.code === 200) {
      product.value = response.data.data;
      sellerId.value = response.data.data.userId;
      username.value = response.data.data.userName;
      productImages.value = [
        response.data.data.image,
        response.data.data.image2,
        response.data.data.image3,
        response.data.data.image4,
        response.data.data.image5,
        response.data.data.image6
      ].filter(image => image); // Filter out any null or empty images
    } else {
      ElMessage.error( '获取商品详情失败: ' + response.data.msg);
    }
  } catch (error) {
    ElMessage.error('获取商品详情失败: ' + error.message);
  }
};

// Function to format date and time
const formatTime = (time) => {
  const date = new Date(time);
  return date.toLocaleString();
};

// Navigate to chat
const gotoChat = (sellerId, username) => {
  if (sellerId !== userStore.UserId) {
    router.push({
      path: '/chat',
      query: {
        userId: sellerId, // Opponent's user ID
        username: username // Opponent's username
      }
    });
  } else {
    ElMessage.error("不能和自己对话");
  }
};

// Add to cart
const addToCart = async () => {
  if (product.value.userId === userStore.UserId) {
    ElMessage.error("不能购买自己的商品");
    return;
  }

  const cartData = {
    userId: userStore.UserId, // Current user's ID
    sellerId: product.value.userId, // Seller's ID
    goodsId: product.value.id, // Product ID
    categoryId: product.value.categoryId, // Product category ID
    image: productImages.value[0], // Use the first product image for the cart
    name: product.value.name, // Product name
    description: product.value.description, // Product description
    price: product.value.price, // Product price
    nums: selectedQuantity.value, // Selected quantity
    type: product.value.type
  };

  try {
    const response = await addCartAPI(cartData); // Call the API function
    if (response.data.code === 200) {
      ElMessage.success('加入购物车成功');
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    ElMessage.error('加入购物车失败: ' + error.msg);
  }
};
const gotoExchange = (buyerId, sellerId, goodsId) => {

  checkExchangeAPI(buyerId, sellerId, goodsId).then(res => {

    if(buyerId === sellerId){
      ElMessage.error("不能和自己交易");
      return;
    }
    if (res.data.code === 200) {
        router.push({
          path: '/exchange',
          query: {
            productId: goodsId // Product ID
          }
        });
      } else {
        ElMessage.error(res.data.msg);
      }

  }).catch(err => {
    ElMessage.error('获取交换记录失败');
  });
};
//跳转到购买页面
const gotoBuy = (goodsId) => {
  if (product.value.userId === userStore.UserId) {
    ElMessage.error("不能购买自己的商品");
    return;
  }
  router.push({
    path: '/buy',
    query: {
      productId: goodsId // Product ID
    }
  });
};

// Initial fetch of product details
fetchProductDetail();
</script>

<style scoped>
.product-image-container {
  position: relative;
  width: 100%;
}

.product-image {
  width: 120%;
  object-fit: cover;
  cursor: pointer;
}

.product-image-container:hover .overlay-text {
  opacity: 1;
}

.overlay-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 8px;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 5px 10px;
  border-radius: 5px;
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
}

.el-card {
  padding: 20px;
  border-radius: 10px;
}

h2 {
  color: #333;
}
</style>
